package com.battle.project.order.threadconfig;

import com.battle.project.order.properties.AsyncThreadPoolProperties;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncThreadPoolTaskExecutor implements AsyncConfigurer {

    @Autowired
    private AsyncThreadPoolProperties threadPoolProperties;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 线程核心线程数
        taskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        // 最大线程数
        taskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        // 设置成true 当线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭
        taskExecutor.setAllowCoreThreadTimeOut(true);
        //允许线程的空闲时间30秒
        taskExecutor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        //任务队列的大小
        taskExecutor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        // 线程前缀名称
        taskExecutor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        //设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        taskExecutor.setAwaitTerminationSeconds(threadPoolProperties.getAwaitTerminationSeconds());
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//         拒绝处理策略
//         CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
//         AbortPolicy()：直接抛出异常。
//         DiscardPolicy()：直接丢弃。
//         DiscardOldestPolicy()：丢弃队列中最老的任务。
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return AsyncConfigurer.super.getAsyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}
